//
//  AppDelegate.m
//  Walk
//
//  Created by cesh on 16/8/23.
//  Copyright © 2016年 cesh. All rights reserved.
//

#import "AppDelegate.h"
#import "WKBubbleViewController.h"
#import "WKCardViewController.h"
#import "WKLoginViewController.h"
#import "JPUSHService.h"
#import "UMMobClick/MobClick.h"
#import "WKNewFeatureViewController.h"
#import <UMSocialCore/UMSocialCore.h>
#import <IQKeyboardManager.h>
#import <EMSDK.h>
#import <AMapFoundationKit/AMapFoundationKit.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //此处设置第一次进入app相关
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"didLogin"];
    }
    else{
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];
    }
    //环信相关设置
    //AppKey:注册的AppKey，详细见下面注释。
    //apnsCertName:推送证书名（不需要加后缀），详细见下面注释。
    EMOptions *options = [EMOptions optionsWithAppkey:@"jungu#walk"];
    options.apnsCertName = @"walk_dev_apns";
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge |
        UIUserNotificationTypeSound |
        UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
    [AMapServices sharedServices].apiKey =@"f381064e38b3520d2f4dab7e244d007b";
    
    // 1.创建窗口
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    // 2.创建根控制器
    //根据是否登录过加载不同的控制器
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"didLogin"]) {
        self.window.rootViewController = [[WKBubbleViewController alloc]init];
        //获取环信账号和密码并登录
        NSDictionary *userInfo = [NSDictionary dictionaryWithContentsOfFile:userInfoPath];
        //环信登录操作
        EMError *error = [[EMClient sharedClient] loginWithUsername:userInfo[@"hx_user"] password:userInfo[@"hx_pwd"]];
        if (!error) {
            NSString *hx_user = userInfo[@"hx_user"];
            NSString *hx_pwd = userInfo[@"hx_pwd"];
            NSLog(@"%@",[NSString stringWithFormat:@"环信登录成功 用户名：%@ 密码：%@",hx_user, hx_pwd]);
            [[EMClient sharedClient] setApnsNickname:userInfo[@"nickname"]];
        }
        else {
            NSLog(@"环信登录失败");
        }
    }else {
        //根据是否是第一次登录加载不同的控制器
        if ([[NSUserDefaults standardUserDefaults]boolForKey:@"firstLaunch"]) {
            self.window.rootViewController = [[WKNewFeatureViewController alloc]init];
        }
        else {
            self.window.rootViewController = [[WKLoginViewController alloc]init];
        }
    }
    // 3.设为可见
    [self.window makeKeyAndVisible];
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
    // 极光推送
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    
    // Required
    //如需兼容旧版本的方式，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化和同时使用pushConfig.plist文件声明appKey等配置内容。
    [JPUSHService setupWithOption:launchOptions appKey:@"0da6ce97acf1545573c0f51a" channel:@"App Store" apsForProduction:@"0"];
    
    [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];
    
    //友盟三方登录设置
    [self UMSet];
    //友盟统计设置
    UMConfigInstance.appKey = @"57e8e383e0f55a1fc9003575";
    UMConfigInstance.channelId = @"App Store";
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    // 对数据加密
    [MobClick setEncryptEnabled:YES];
    
    return YES;
}

- (void)UMSet {
    //打开调试日志
    [[UMSocialManager defaultManager] openLog:YES];
    
    //设置友盟appkey
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"57e8e383e0f55a1fc9003575"];
    
    // 获取友盟social版本号
    //NSLog(@"UMeng social version: %@", [UMSocialGlobal umSocialSDKVersion]);
    
    //设置微信的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx67ea308a62557fa3" appSecret:@"5f07b68a709045c38be3eeb75d8e0721" redirectURL:@"http://mobile.umeng.com/social"];
    
    //设置分享到QQ互联的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1105652628"  appSecret:@"h3ebcOhsResX3lGw" redirectURL:@"http://mobile.umeng.com/social"];
}
//系统回调 
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"deviceToken %@", deviceToken);
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
    [[EMClient sharedClient] bindDeviceToken:deviceToken];
}



- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[EMClient sharedClient] applicationDidEnterBackground:application];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [[EMClient sharedClient] applicationWillEnterForeground:application];
    [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    //退出程序的时候清空经纬度
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"coordinates"];
}

@end
